package com.nl.controller.xuyi.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nl.controller.common.model.BaseResult;
import com.nl.controller.common.redis.RedisCluster;
import com.nl.controller.common.util.MD5;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.global.GlobalConstants;
import com.nl.controller.web.util.StringUtil;
import com.nl.controller.xuyi.bean.XuYiOperatorInfo;
import com.nl.controller.xuyi.bean.pocbo.*;
import com.nl.controller.xuyi.bean.pocreq.*;
import com.nl.controller.xuyi.bean.pocreqboby.*;
import com.nl.controller.xuyi.mapper.XuYiOperatorMapper;
import com.nl.controller.xuyi.mapper.XuYiPocMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.security.MD5Encoder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
/**
 * @desc
 * @return POC平台信息接口
 * @author ll
 * @date 2020/9/20 16:57
 */
public class XuYiPocService {
    @Autowired
    XuYiOperatorMapper xuYiOperatorMapper;

    @Autowired
    XuYiPocMapper xuYiPocMapper;
    // 地球半径,单位千米
    private static final double EARTH_RADIUS = 6378.137;
    private static double rad(double d) {
        //角度转换成弧度
        return d * Math.PI / 180.0;
    }

    /**
     * @desc PoC入驻平台接入鉴权
     
     * @return com.nl.controller.common.model.BaseResult<java.lang.String>
     * @author ll
     * @date 2020/9/17 19:45
     */
    public BaseResult<String> getPocAuth() {
        BaseResult<String> result = BaseResult.newFailInstance();
        RedisCluster redisCluster=null;
        //有效的serviceCode;
        String serviceCode = "";
        try {
            //判断redis中是否存在有效的serviceCode
            redisCluster = new RedisCluster(GlobalConst.REDIS_CONFIG);
            serviceCode = redisCluster.get("ServiceCode");
            if (!StringUtil.isNull(serviceCode)) {
                //redis中有值则取值返回，无值则去请求接口
                result.setRetCode(GlobalConstants.SUCCESS_CODE);
                result.setRetMsg("serviceCode未过期，获取redis中serviceCode");
                result.setData(serviceCode);
                log.info("serviceCode未过期，获取redis中serviceCode");
            } else {
                GetPocAuthReq getPocAuthReq = new GetPocAuthReq();
                GetPocAuthBody getPocAuthBody = new GetPocAuthBody();
                getPocAuthBody.setHostIp(GlobalConstants.ESMS_HOST_IP);
                getPocAuthBody.setCustomId(GlobalConstants.ESMS_CUSTOM_ID);
                getPocAuthBody.setCustomPwd(GlobalConstants.ESMS_CUSTOM_PSD);
                getPocAuthReq.setCode(10000);
                getPocAuthReq.setBody(getPocAuthBody);
                //转化为json
                ObjectMapper mapper = new ObjectMapper();
                String mapJakcson = mapper.writeValueAsString(getPocAuthReq);
                JSONObject jsonObject = new JSONObject();
                jsonObject = JSON.parseObject(mapJakcson);
                log.info("getPocAuth interface request:" + jsonObject.toJSONString());
                //请求接口
                String resp = CommonService.httpPostWithJson(GlobalConstants.POC_URL, jsonObject);
                log.info("获取serviceCode返回数据,resp=" + resp);
                if (!StringUtils.isEmpty(resp)) {
                    JSONObject respJson = JSONObject.parseObject(resp);
                    int respResult = respJson.getIntValue("Result");
                    serviceCode = respJson.getString("ServiceCode");
                    log.info("Poc平台接入鉴权接口返回数据,result=" + respResult + ",ServiceCode=" + serviceCode);
                    if(200==respResult){
                        result.setRetCode(GlobalConstants.SUCCESS_CODE);
                        result.setRetMsg("Poc平台接入鉴权接口返回数据,serviceCode=" + serviceCode);
                        result.setData(serviceCode);
                        //将获取到的有效的serviceCode存于redis中，有效期一个小时
                        redisCluster.set("ServiceCode",serviceCode);
                        redisCluster.expire("ServiceCode",3600);
                    }else{
                        result.setRetCode(String.valueOf(respResult));
                        result.setRetMsg("Poc平台接入鉴权接口返回数据,result=" + respResult);
                    }
                } else {
                    result.setRetMsg("Poc平台接入鉴权接口返回数据为空");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setRetMsg("Poc平台接入鉴权接口出现异常:" + e.getMessage());
        }finally{
            try {
                redisCluster.close();
            } catch (IOException e) {
                e.printStackTrace();
                result.setRetMsg("redisCluster关闭发生异常:" + e.getMessage());
            }
        }
        return result;
}

    /**
     * @desc 调度员获取Session信息
     * @return com.nl.controller.common.model.BaseResult<java.lang.Object>
     * @author ll
     * @date 2020/9/20 16:57
     */
    public BaseResult<String> getSessionId(){
        //获取serviceCode;
        String serviceCode = this.getPocAuth().getData();
        RedisCluster redisCluster=null;
        BaseResult<String> result = BaseResult.newFailInstance();
        String sessionId = "" ;
        try{
            redisCluster = new RedisCluster(GlobalConst.REDIS_CONFIG);
            sessionId = redisCluster.get("sessionId");
            if (!StringUtil.isNull(sessionId)) {
                //redis中有值则取值返回，无值则去请求接口
                result.setRetCode(GlobalConstants.SUCCESS_CODE);
                result.setRetMsg("sessionId未过期，获取redis中sessionId");
                result.setData(sessionId);
                log.info("sessionId未过期，获取redis中sessionId");
            } else {

                GetSessionIdReq getSessionIdReq = new GetSessionIdReq();
                GetSesssionIdBody getSesssionIdBody = new GetSesssionIdBody();
                getSesssionIdBody.setServiceCode(serviceCode);
                getSesssionIdBody.setDispatcherId(GlobalConstants.POC_DISPATCHER_ID);
                getSesssionIdBody.setDispatcherPwd(GlobalConstants.POC_DISPATCHER_PWD);
                getSessionIdReq.setCode(10010);
                getSessionIdReq.setBody(getSesssionIdBody);
                //转化为json
                ObjectMapper mapper = new ObjectMapper();
                String mapJakcson = mapper.writeValueAsString(getSessionIdReq);
                JSONObject jsonObject = new JSONObject();
                jsonObject = JSON.parseObject(mapJakcson);
                log.info("getSessionId interface request:" + jsonObject.toJSONString());
                //请求接口
                String resp = CommonService.httpPostWithJson(GlobalConstants.POC_URL, jsonObject);

                log.info("获取sessionId返回数据,resp=" + resp);
                if (!StringUtils.isEmpty(resp)) {
                    QrySessionIdResp qrySessionIdResp = JSONObject.parseObject(resp, QrySessionIdResp.class);
                    int respResult = qrySessionIdResp.getResult();
                    sessionId = qrySessionIdResp.getSessionId();
                    log.info("调度员获取Session信息返回数据,result=" + respResult + ",SessionId=" + sessionId);
                    if(200==respResult){
                        result.setRetCode(GlobalConstants.SUCCESS_CODE);
                        result.setRetMsg("调度员获取Session信息返回数据,SessionId=" + sessionId);
                        result.setData(sessionId);
                        redisCluster.set("SessionId",sessionId);
                        redisCluster.expire("SessionId",3600);
                    }else{
                        result.setRetCode(String.valueOf(respResult));
                        result.setRetMsg("调度员获取Session信息返回数据,result=" + respResult);
                    }
                } else {
                    result.setRetMsg("调度员获取Session信息返回数据为空");
                }
            }
        }catch(Exception e){
            e.printStackTrace();
            log.info("获取sessionId出现异常："+e.toString());
        }
        return result;
    }






    /**
     * @desc 获取运维人员当前位置信息
     * @return com.nl.controller.common.model.BaseResult<java.util.List<com.nl.controller.xuyi.bean.pocbo.LocationInfoBo>>
     * @author ll
     * @date 2020/9/24 17:24
     */
    public BaseResult<List<LocationInfoBo>> qryNowLocation(LocationRequest locationRequest){
        BaseResult<List<LocationInfoBo>> result = BaseResult.newFailInstance();
        List<LocationInfoBo> locationInfoList ;
        String uid;
        String name ;
        QryYunWeiListDispatcher yunWeiListDispatcher = new QryYunWeiListDispatcher();
        List<String> uidsList = new ArrayList<>();
        try{
            if(!CollectionUtils.isEmpty(locationRequest.getUidList())) {
                uidsList = locationRequest.getUidList();
                //获取有效的sessionId
                String sessionId = this.getSessionId().getData();
                //封装参数
                GetNowLocationReq getNowLocationReq = new GetNowLocationReq();
                GetNowLocationBody getNowLocationBody = new GetNowLocationBody();
                getNowLocationBody.setSessionId(sessionId);
                getNowLocationBody.setUids(uidsList);
                getNowLocationReq.setCode(10200);
                getNowLocationReq.setBody(getNowLocationBody);
                //转化为json
                ObjectMapper mapper = new ObjectMapper();
                String mapJakcson = mapper.writeValueAsString(getNowLocationReq);
                JSONObject jsonObject = new JSONObject();
                jsonObject = JSON.parseObject(mapJakcson);
                log.info("qryNowLocation interface request:" + jsonObject.toJSONString());
                //请求接口
                String resp = CommonService.httpPostWithJson(GlobalConstants.POC_URL, jsonObject);
               //MOCK数据
                //String resp = "{\"Result\":\"200\",\"Locations\":[{\"uid\":\"13877615333\",\"name\":\"测试账户1\",\"gpsLongitude\":\"118.533334\",\"gpsLatitude\":\"31.111111\",\"baiduLongitude\":\"118.533334\",\"baiduLatitude\":\"33.003359\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"},{\"uid\":\"13877615253\",\"name\":\"测试账户2\",\"gpsLongitude\":\"118.111111\",\"gpsLatitude\":\"31.111111\",\"baiduLongitude\":\"118.533415\",\"baiduLatitude\":\"33.005237\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}]}";

                log.info("获取运维人员当前位置返回数据,resp=" + resp);
                if (!StringUtils.isEmpty(resp)) {
                    QryNowLocationResp qryNowLocationResp = JSONObject.parseObject(resp,QryNowLocationResp.class);
                    if (GlobalConstants.POC_SUCCESS_CODE.equals(qryNowLocationResp.getResult())){
                        result.setRetCode(GlobalConstants.SUCCESS_CODE);
                        locationInfoList = qryNowLocationResp.getLocations();
                        //封装运维名称
                        for(LocationInfoBo locationInfoBo : locationInfoList){
                            uid=locationInfoBo.getUid();
                            yunWeiListDispatcher.setUid(uid);
                            name = xuYiPocMapper.findYunWeiList(yunWeiListDispatcher).get(0).getName();
                            name = (name.isEmpty()?"暂无运维名称":name);
                            locationInfoBo.setName(name);
                        }
                        result.setData(locationInfoList);
                        result.setRetMsg("获取运维人员当前位置返回数据成功");
                        log.info("获取运维人员当前位置返回数据成功!");

                    }else{
                        result.setRetMsg("获取运维人员当前位置返回数据,result=" + qryNowLocationResp.getResult());
                        log.info("获取运维人员当前位置未成功，result ="+qryNowLocationResp.getResult());
                    }
                }else{
                    result.setRetMsg("获取运维人员当前位置返回数据为空");
                    log.info("获取运维人员当前位置返回数据为空");
                }
            }
        }catch(Exception e){
                result.setRetMsg("获取运维人员当前位置发生异常："+e.toString());
                e.printStackTrace();
        }
        return result;
    }

    /**
     * @desc 获取运维人员历史轨迹信息
     * @return com.nl.controller.common.model.BaseResult<java.util.Map<java.lang.String,java.util.List<com.nl.controller.xuyi.bean.pocbo.LocationInfoBo>>>
     * @author ll
     * @date 2020/9/24 17:23
     */
    public BaseResult<Map<String,List<LocationInfoBo>>> qryHisLocation(LocationRequest locationRequest){
        BaseResult<Map<String,List<LocationInfoBo>>> result = BaseResult.newFailInstance();
        Map<String,List<LocationInfoBo>> map = new HashMap<String,List<LocationInfoBo>>();

        List<LocationInfoBo> locationInfoList ;
        List<String> uidsList = locationRequest.getUidList();
        int count = 0;
        String uids = locationRequest.getUids();
        try {
            //查看指定人员历史位置数据
            if(!CollectionUtils.isEmpty(uidsList)) {
                //给定输出格式
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                Date now = new Date();
                String now2 = sdf.format(now);

                Long time = System.currentTimeMillis();
                //取半个小时以前的时间
                time = time - 24*60*60*1000;
                String thirtyAgo = sdf.format(time);
                /*Calendar c = Calendar.getInstance();
                c.setTime(now);
                c.add(Calendar.DAY_OF_MONTH, -1/48);
                //这是昨天
                Date yesterday = c.getTime();
                String yesterday2 = sdf.format(yesterday);*/
                //获取有效的sessionId
                String sessionId = this.getSessionId().getData();
                GetHisLocationReq getHisLocationReq = new GetHisLocationReq();
                GetHisLocationBody getHisLocationBody = new GetHisLocationBody();
                getHisLocationBody.setSessionId(sessionId);
                getHisLocationBody.setPageIndex(0);
                getHisLocationBody.setPageSize(1000);
                //0：全部；1：GPS坐标；2：基站坐标
                getHisLocationBody.setLocationType(1);
                getHisLocationBody.setTimeFrom(locationRequest.getTimeFrom());
                getHisLocationBody.setTimeTo(locationRequest.getTimeTo());


                for (String uid : uidsList) {
                    if (!StringUtil.isNull(uid)) {
                        getHisLocationBody.setUid(uid);
                        getHisLocationReq.setCode(10201);
                        getHisLocationReq.setBody(getHisLocationBody);
                        //转化为json
                        ObjectMapper mapper = new ObjectMapper();
                        String mapJakcson = mapper.writeValueAsString(getHisLocationReq);
                        JSONObject jsonObject = new JSONObject();
                        jsonObject = JSON.parseObject(mapJakcson);
                        log.info("qryHisLocation interface request:" + jsonObject.toJSONString());
                        //请求接口
                        String resp = CommonService.httpPostWithJson(GlobalConstants.POC_URL, jsonObject);
                        //Mock数据
                                                                                            //118.532363,33.005097   118.532785,33.006044  118.533302,33.00744  118.53376,33.008428 118.535278,33.007944
                                                                                                //118.536513,33.007614   118.537717,33.007224  118.53827,33.01004   118.537371,33.010161   118.537497,33.010918
                        /*String resp = "{\"Result\":200,\"PageTotalCount\":13,\"Locations\":[{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.532363\",\"baiduLatitude\":\"33.005097\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.532785\",\"baiduLatitude\":\"33.006044\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.533302\",\"baiduLatitude\":\"33.00744\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.53376\",\"baiduLatitude\":\"33.008428\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.535278\",\"baiduLatitude\":\"33.007944\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.536513\",\"baiduLatitude\":\"33.007614\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.537717\",\"baiduLatitude\":\"33.007224\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.53827\",\"baiduLatitude\":\"33.01004\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.537371\",\"baiduLatitude\":\"33.010161\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}," +
                                "{\"uid\":\"13877615253\",\"gpsLongitude\":\"31.111111\",\"gpsLatitude\":\"118.111111\",\"baiduLongitude\":\"118.537497\",\"baiduLatitude\":\"33.010918\",\"time\":\"2016-05-1616:34:08\",\"type\":\"2\"}]}"
                                ;*/
                        log.info("获取运维人员历史位置返回数据,resp=" + resp);
                        if(!StringUtil.isNull(resp)){
                            QryHisLocationResp qryHisLocationResp = JSONObject.parseObject(resp,QryHisLocationResp.class);
                            if (GlobalConstants.POC_SUCCESS_CODE.equals(qryHisLocationResp.getResult())){
                                locationInfoList = qryHisLocationResp.getLocations();
                                map.put(uid,locationInfoList);
                                count++;
                                log.info("获取运维人员历史位置返回数据成功!--uid = "+uid);
                            }else{
                                log.info("获取运维人员历史位置未成功，result ="+qryHisLocationResp.getResult()+"uid="+uid);
                            }
                        }else{
                            log.info("获取运维人员历史位置返回数据为空,uid="+uid);
                        }

                    }else{
                        //查询全量运维历史位置数据
                    }
                }
                if(!map.isEmpty()){
                    result.setRetMsg("获取运维人员历史位置返回数据成功,共获取"+count+"个运维人员的历史位置集合");
                    log.info("获取运维人员历史位置返回数据成功,共获取"+count+"个运维人员的历史位置集合");

                }else{
                    result.setRetMsg("获取运维人员历史位置返回数据为空");
                    log.info("获取运维人员历史位置返回数据为空");

                }
                result.setRetCode(GlobalConstants.SUCCESS_CODE);
                result.setData(map);
            }
        }catch (Exception e){
            result.setRetMsg("获取运维人员历史位置发生异常："+e.toString());
            e.printStackTrace();
        }
        return result;
    }

    public BaseResult<List<QryYunWeiListDispatcher>> qryYunWeiList2(String name){
        BaseResult<List<QryYunWeiListDispatcher>> result = BaseResult.newSuccessInstance();
        QryYunWeiListDispatcher yunWeiInfo =  new QryYunWeiListDispatcher();
        try {
            yunWeiInfo.setName(name);
            List<QryYunWeiListDispatcher> yunweiList = xuYiPocMapper.findYunWeiList(yunWeiInfo);
            result.setData(yunweiList);
        }catch (Exception e){
            log.info("从表中获取运维人员列表发生异常:"+e.getMessage());
            e.printStackTrace();
        }
        return result;
    }

    /**
     * @desc 通过接口获取运维人员列表
     * @param name
     * @return com.nl.controller.common.model.BaseResult<java.util.List<com.nl.controller.xuyi.bean.pocbo.QryYunWeiListDispatcher>>
     * @author ll
     * @date 2020/9/23 14:42
     */
    public BaseResult<List<QryYunWeiListDispatcher>> qryYunWeiList(String name) {
        BaseResult<List<QryYunWeiListDispatcher>> result = BaseResult.newFailInstance();
        List<QryYunWeiListDispatcher> dispatchersList = new ArrayList<>();
        List<QryYunWeiListDispatcher> matchDispatchersList = new ArrayList<>();
        List<OrgInfo> orgsLists ;
        List<XuYiOperatorInfo> operatorInfosList ;
        XuYiOperatorInfo  operatorInfo;
        String sessionId="";
        List list = new ArrayList();

        try {
            sessionId= this.getSessionId().getData();

            GetYunWeiListReq getYunWeiListReq = new GetYunWeiListReq();
            GetYunWeiListBody getYunWeiListBody = new GetYunWeiListBody();
            getYunWeiListBody.setSessionId(sessionId);
            getYunWeiListReq.setCode(10116);
            getYunWeiListReq.setBody(getYunWeiListBody);
            //转化为json
            ObjectMapper mapper = new ObjectMapper();
            String mapJakcson = mapper.writeValueAsString(getYunWeiListReq);
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(mapJakcson);
            log.info("qryYunWeiList interface request:" + jsonObject.toJSONString());
            //请求接口
            String resp = CommonService.httpPostWithJson(GlobalConstants.POC_URL, jsonObject);
            //Mock数据
            //String resp = "{\"Result\":200,\"Orgs\":[{\"Id\":818,\"ParentId\":817,\"Name\":\"测试子组织1\",\"Users\":[{\"Uid\":\"13877615253\",\"Name\":\"测试账户1\"},{\"Uid\":\"13877615333\",\"Name\":\"测试账户2\"}]}]}";
            log.info("获取运维人员列表返回数据,resp=" + resp);
            if (!StringUtils.isEmpty(resp)) {
                QryYunWeiListResp2 yunWeiListResp = JSONObject.parseObject(resp, QryYunWeiListResp2.class);
                if (GlobalConstants.POC_SUCCESS_CODE.equals(yunWeiListResp.getResult())){
                    result.setRetCode(GlobalConstants.SUCCESS_CODE);
                    orgsLists = yunWeiListResp.getOrgs();
                    if(!CollectionUtils.isEmpty(orgsLists)){
                        for(OrgInfo org : orgsLists){
                            dispatchersList = org.getUsers();
                            if(!CollectionUtils.isEmpty(dispatchersList)){
                                //前台按照运维人员名称进行搜索
                                if(!StringUtil.isNull(name)){
                                    for(QryYunWeiListDispatcher dispatcher : dispatchersList){
                                        String dispatcherName = dispatcher.getName();
                                        if(dispatcherName.contains(name)){
                                            matchDispatchersList.add(dispatcher);
                                        }
                                        if(dispatcher.getUid().equals("7207810001")){
                                            //管理员，无需展示
                                            continue;
                                        }
                                    }
                                    //按照名称搜索时，返回匹配的数据
                                    result.setData(matchDispatchersList);
                                }else{
                                    //未按照名称搜索时，返回全量数据
                                    for(QryYunWeiListDispatcher dispatcher : dispatchersList){
                                        if(dispatcher.getUid().equals("7207810001")){
                                            //管理员，无需展示
                                            continue;
                                        }
                                        matchDispatchersList.add(dispatcher);
                                    }
                                    result.setData(matchDispatchersList);
                                }
                                result.setRetCode(GlobalConstants.SUCCESS_CODE);
                                result.setRetMsg("获取运维人员列表返回数据成功");
                                log.info("获取运维人员列表成功!");
                            }else{
                                result.setRetMsg("获取运维人员列表返回数据中运维人员列表为空");
                                log.info("获取运维人员列表返回数据中运维人员列表为空");
                            }
                        }
                    }else{
                        result.setRetMsg("获取运维人员列表返回数据中Orgs为空");
                        log.info("获取运维人员列表返回数据中Orgs为空");
                    }

                }else{
                    result.setRetMsg("获取运维人员列表返回数据,result=" + yunWeiListResp.getResult());
                    log.info("获取运维人员列表未成功，result ="+yunWeiListResp.getResult());
                }
            } else {
                result.setRetMsg("获取运维人员列表返回数据为空");
                log.info("获取运维人员列表返回数据为空");
            }
        } catch (Exception e) {
            result.setRetMsg("获取运维人员列表发生异常："+e.toString());
            e.printStackTrace();

        }
        return result;
    }


    /**
     * 计算两个地点的距离
     *
     * @param lng1 第一个经度
     * @param lat1 第一个纬度
     * @param lng2 第二个经度
     * @param lat2 第二个纬度
     * @return 两个经纬度的距离
     */
    private static Double judgeDistance(Double length, double lng1, double lat1, double lng2, double lat2) {
        Double result =-1.0;
        //纬度
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        //两点纬度之差
        double a = radLat1 - radLat2;
        //经度之差
        double b = rad(lng1) - rad(lng2);
        //计算两点之间距离的公式
        double s = 2 * Math.asin(Math.sqrt(
                Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        //弧长乘地球半径（半径）
        s = s * EARTH_RADIUS;
        //精确距离的数值（单位千米）
        s =  s*1000;
        if(length - s>=0.0){
            result = s;
        }
        return result;
    }
    
    /**
     * @desc 根据范围查询运维人员
     * @param circleInfo 
     * @return com.nl.controller.common.model.BaseResult<java.util.List<com.nl.controller.xuyi.bean.pocbo.QryYunWeiListDispatcher>>
     * @author ll
     * @date 2020/9/25 9:00
     */
    public BaseResult<List<QryYunWeiListDispatcher>> qryYunWeiByLocation(CircleInfo circleInfo) {
        String length = circleInfo.getLength();
        String centerLng = circleInfo.getLongitude();
        String centerLat = circleInfo.getLatitude();
        BaseResult<List<QryYunWeiListDispatcher>> result = BaseResult.newFailInstance();
        List<QryYunWeiListDispatcher> matchYunWeiList = new ArrayList<>();
        BaseResult<List<QryYunWeiListDispatcher>> yunWeiResp = this.qryYunWeiList2("");
        BaseResult<List<LocationInfoBo>> locationInfoResp ;
        List<LocationInfoBo> locationInfoList ;
        Map<String,QryYunWeiListDispatcher> yunWeiMap = new HashMap<>();
        List<QryYunWeiListDispatcher> yunWeiList = yunWeiResp.getData();
        LocationRequest locationRequest = new LocationRequest();
        List<String> uidsList = new ArrayList<>();
        Map<String,Object> compareResp;
        Boolean compareResult;
        Double distance;

        if(!CollectionUtils.isEmpty(yunWeiList)){
            for(QryYunWeiListDispatcher yunWeiInfo : yunWeiList){
                String uid = yunWeiInfo.getUid();
                yunWeiMap.put(uid,yunWeiInfo);
                uidsList.add(uid);
            }
        }
        locationRequest.setUidList(uidsList);
        locationInfoResp = this.qryNowLocation(locationRequest);
        locationInfoList = locationInfoResp.getData();
        for(LocationInfoBo locationInfo : locationInfoList){
            String uid = locationInfo.getUid();
            String lng = locationInfo.getBaiduLongitude();
            String lat = locationInfo.getBaiduLatitude();
            String type = locationInfo.getType();
            //判断是否是有效的定位数据，-1为无效
            if("-1".equals(type)){
                continue;
            }
            distance = judgeDistance(Double.parseDouble(length),Double.parseDouble(centerLng),Double.parseDouble(centerLat),Double.parseDouble(lng),Double.parseDouble(lat));
            //compareResult = true;
            //compareResult = (Boolean)compareResp.get("compareResult");
            //Mock

            if(distance!=-1.0){
                if(yunWeiMap.containsKey(uid)){
                    yunWeiMap.get(uid).setLongitude(lng);
                    yunWeiMap.get(uid).setLatitude(lat);
                    yunWeiMap.get(uid).setDistance(String.valueOf((Math.floor(distance*10))/10));
                    matchYunWeiList.add(yunWeiMap.get(uid));
                }
            }
        }
        result.setRetCode(GlobalConstants.SUCCESS_CODE);
        result.setData(matchYunWeiList);
        if(CollectionUtils.isEmpty(matchYunWeiList)){
            result.setRetMsg("范围内无运维人员");
        }else{
            result.setRetMsg("范围内有"+matchYunWeiList.size()+"个运维人员");
        }
        return result;
    }

    /**
     * @desc 同步全量运维人员入库，24小时
     * @return int 数量
     * @author ll
     * @date 2020/10/8 16:39
     */
    public int synYunWeiList() {
        int deleteResult = 0;
        int insertResult = 0;
        int insertCount = 0;

        //获取全量运维人员数据
        BaseResult<List<QryYunWeiListDispatcher>> yunWeiListResp=this.qryYunWeiList("");
        List<QryYunWeiListDispatcher> yunWeiList;
        if((GlobalConstants.SUCCESS_CODE).equals(yunWeiListResp.getRetCode())){
            yunWeiList = yunWeiListResp.getData();
            if(!CollectionUtils.isEmpty(yunWeiList)){
                //先删除旧数据
                deleteResult= xuYiPocMapper.deleteYunWei();
                //插入新数据
                for(QryYunWeiListDispatcher yunWeiInfo : yunWeiList){
                    insertResult= xuYiPocMapper.insertYunWei(yunWeiInfo);
                    if(insertResult>0){
                        insertCount++;
                    }
                }
            }
        }
        return insertCount;
    }




    public static void main(String[] args) throws JsonProcessingException {

        MD5 md5 = new MD5();
        System.out.println(md5.getMD5ofStr("62nzIO--"));

//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date now = new Date();
//        String today = sdf.format(now);
//        Calendar c = Calendar.getInstance();
//        c.setTime(now);
//        c.add(Calendar.HOUR_OF_DAY,-1);
//        //这是昨天
//        Date yesterday = c.getTime();
//        String yesterday2 = sdf.format(yesterday);
//        System.out.println(yesterday2);
//
//        Long time =System.currentTimeMillis();
//        time = time -30*1000*60;
//        System.out.println(sdf.format(time));

/*        try {

            System.out.println("太原－上海：" + judgeDistance(37.97111222, 112.5323322, 31.22323332, 121.4832333));
            //System.out.println("宁波－上海：" + getDistance(29.86, 121.56, 31.22, 121.48));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/


        //给定输出格式
        /*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        String today = sdf.format(now);
        Calendar c = Calendar.getInstance();
        c.setTime(now);
        c.add(Calendar.DAY_OF_MONTH, -1);
        //这是昨天
        Date yesterday = c.getTime();
        String yesterday2 = sdf.format(yesterday);
        System.out.println(yesterday2);
        String resp ="{\n" +
                "  \"Result\": 200,\n" +
                "  \"Dispatcher\":\n" +
                "  [\n" +
                "{\"Uid\": \"100110002\", \"Name\": \"调度员002\"},\n" +
                "{\"Uid\": \"100110003\", \"Name\": \"调度员003\"}\n" +
                "  ]\n" +
                "}";
        QryYunWeiListResp yunWeiListResp = JSONObject.parseObject(resp, QryYunWeiListResp.class);
        System.out.println(yunWeiListResp.toString());

        GetSesssionIdBody getSesssionIdBody = new GetSesssionIdBody();
        JSONObject jsonObject = new JSONObject();
        JSONObject jsonObject2 = new JSONObject();
        /*jsonObject2.put("DispatcherPwd","JhDU7DF9Ao5BSdf152Bdl");
        jsonObject2.put("DispatcherId","1000110");
        jsonObject2.put("ServiceCode","33761652662884");
        GetSessionIdReq getSessionIdReq = new GetSessionIdReq();

        getSesssionIdBody.setServiceCode("33761652662884");
        getSesssionIdBody.setDispatcherId("1000110");
        getSesssionIdBody.setDispatcherPwd("JhDU7DF9Ao5BSdf152Bdl");
        getSessionIdReq.setCode(10010);
        getSessionIdReq.setBody(getSesssionIdBody);
        ObjectMapper mapper = new ObjectMapper();
        String mapJakcson = mapper.writeValueAsString(getSessionIdReq);
        //System.out.println(mapJakcson);
        jsonObject2 = JSON.parseObject(mapJakcson);
        log.info("qryYunWeiList interface request:" + jsonObject2.toJSONString());
        //log.info("qryYunWeiList interface request:" + jsonObject.toJSONString());
        */

    }

    /*    public BaseResult<List<QryYunWeiListDispatcher>> qryYunWeiList(String name) {
        BaseResult<List<QryYunWeiListDispatcher>> result = BaseResult.newFailInstance();
        List<QryYunWeiListDispatcher> dispatchersList = new ArrayList<>();
        List<XuYiOperatorInfo> operatorInfosList ;
        XuYiOperatorInfo  operatorInfo;
        String pocUrl = GlobalConstants.POC_URL;
        String sessionId="";
        List list = new ArrayList();

        try {
            sessionId = this.getSessionId().getData();

            GetDispatcherListReq getDispatcherListReq = new GetDispatcherListReq();
            GetDispatcherListBody getDispatcherListBody = new GetDispatcherListBody();
            getDispatcherListBody.setSessionId(sessionId);
            getDispatcherListReq.setCode(10011);
            getDispatcherListReq.setBody(getDispatcherListBody);
            //转化为json
            ObjectMapper mapper = new ObjectMapper();
            String mapJakcson = mapper.writeValueAsString(getDispatcherListReq);
            JSONObject jsonObject = new JSONObject();
            jsonObject = JSON.parseObject(mapJakcson);
            log.info("qryYunWeiList interface request:" + jsonObject.toJSONString());
            //请求接口
            String resp = CommonService.httpPostWithJson(pocUrl, jsonObject);
            log.info("获取调度员列表返回数据,resp=" + resp);
            if (!StringUtils.isEmpty(resp)) {
                QryYunWeiListResp yunWeiListResp = JSONObject.parseObject(resp, QryYunWeiListResp.class);
                if (GlobalConstants.POC_SUCCESS_CODE.equals(yunWeiListResp.getResult())){
                    result.setRetCode(GlobalConstants.SUCCESS_CODE);
                    dispatchersList = yunWeiListResp.getDispatcher();
                    if(!CollectionUtils.isEmpty(dispatchersList)){
                        //前台按照运维人员名称进行搜索
                        if(!StringUtil.isNull(name)){
                            for(QryYunWeiListDispatcher dispatcher : dispatchersList){
                                String dispatcherName = dispatcher.getName();
                                if(name.equals(dispatcherName)){
                                    dispatchersList.clear();
                                    dispatchersList.add(dispatcher);
                                }
                            }
                        }


                        for(QryYunWeiListDispatcher dispatcher : dispatchersList){
                            String uid = dispatcher.getUid();

                            //根据和对讲编码查询运维人员手机号
                            if(!StringUtils.isEmpty(uid)){
                                Map map1 = new HashMap();
                                map1.put("talkingCoding",uid);
                                operatorInfosList= xuYiOperatorMapper.findOperator(map1);
                                if(!CollectionUtils.isEmpty(operatorInfosList)){
                                    operatorInfo= operatorInfosList.get(0);
                                    dispatcher.setPhoneNumber(operatorInfo.getOperatorMsisdn());
                                }
                            }
                        }
                        result.setRetCode(GlobalConstants.SUCCESS_CODE);
                        result.setData(dispatchersList);
                        result.setRetMsg("获取调度员列表返回数据成功");
                        log.info("获取调度员列表成功!");
                    }else{
                        result.setRetMsg("获取调度员列表返回数据中调度员列表为空");
                        log.info("获取调度员列表返回数据中调度员列表为空");
                    }

                }else{
                    result.setRetMsg("获取调度员列表返回数据,result=" + yunWeiListResp.getResult());
                    log.info("获取调度员列表未成功，result ="+yunWeiListResp.getResult());
                }
            } else {
                result.setRetMsg("获取调度员列表返回数据为空");
                log.info("获取调度员列表返回数据为空");
            }
        } catch (Exception e) {
            result.setRetMsg("获取调度员列表发生异常："+e.toString());
            e.printStackTrace();

        }
        return result;
    }*/


}
